<template>
	<view class="add">
		<form @submit="onSubmit">
			<view class="item">
				<input v-model="formValue.title" type="text" name="title" placeholder="请输入标题"></input>
			</view>

			<view class="item">
				<input v-model="formValue.author" type="text" name="author" placeholder="请输入作者"></input>
			</view>

			<view class="item">
				<textarea v-model="formValue.content" name="content" placeholder="请输入详细内容"></textarea>
			</view>

			<view class="item">
				<uni-file-picker v-model="imageValue" ref="files" :autoUpload="false" :limit="3" fileMediatype="image"
					mode="grid" returnType="array" fileExtname="jpg,png,gif,webp" title="可选图片数量" @select="selectFiles"
					@success="uploadFilesSuccess" />
			</view>

			<view class="item">
				<button form-type="reset" @click="resetFormValue">重置</button>
				<button form-type="submit" type="primary" :disabled="inDisabled(formValue)">提交</button>
			</view>
		</form>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				imageValue: [],
				picurls: [],
				formValue: {
					title: "",
					author: "",
					content: ""
				}
			};
		},
		watch: {
			// 使用watch来响应数据的变化
			imageValue(newVal, oldVal) {
				console.log(newVal);
				this.imageValue = newVal
			}
		},
		methods: {
			// 重置formValue的值
			resetFormValue() {
				this.formValue = {
					title: "",
					author: "",
					content: ""
				}
				this.imageValue = []
			},
			//判断按钮是否禁用
			inDisabled(obj) {
				let bool = Object.keys(obj).some((key, value) => {
					return obj[key] == ''
				})
				return bool;
			},
			onSubmit(e) {
				let detail = e.detail.value
				uni.showToast({
					icon: "loading",
					title: "正在上传"
				})
				new Promise(async (resolve, reject) => {
					try {
						await this.$refs.files.upload()
						await uniCloud.callFunction({
							name: "CloudArticle-add_row",
							data: {
								detail,
								picurls: this.picurls
							}
						})
						resolve();
					} catch (e) {
						reject(e);
					}
				}).then(() => {
					uni.showToast({
						title: "发布成功"
					})
				}).catch((e) => {
					uni.showToast({
						icon: "error",
						title: "发布失败"
					})
				}).finally(() => {
					this.imageValue = []
					this.picurls = []
					setTimeout(() => {
						uni.hideToast();
						uni.reLaunch({
							url: "/pages/index/index"
						})
					}, 500)
				})
			},
			selectFiles(e) {
				let oldImageValue = this.imageValue
				this.imageValue = [...oldImageValue, ...e.tempFiles]
			},
			uploadFilesSuccess(e) {
				this.picurls = e.tempFilePaths
			}
		}
	}
</script>

<style lang="scss" scoped>
	.add {
		padding: 30rpx;

		.item {
			padding-bottom: 20rpx;

			input,
			textarea {
				border: 1rpx solid #eee;
				height: 80rpx;
				padding: 0 20rpx;
			}

			textarea {
				height: 200rpx;
				width: 100%;
				box-sizing: border-box;
			}

			button {
				margin-bottom: 20rpx;
			}
		}
	}
</style>